#include "adc_power.h"
esp_adc_cal_characteristics_t *adc_chars;
char char_adc0[10]; 
char char_adc1[10]; 
char udp_char_adc0[15]; 
char udp_char_adc1[15]; 

char voltageString0[] = "Voltage0:";
char voltageString1[] = "Voltage1:";
char powerString[] = "Power_mW:";
uint16_t power_mw = 0;
char char_power_mw[10]; 
char udp_char_power[15]; 

void ADC_power_init(){
  adc1_config_width(ADC_WIDTH);  // 设置ADC为12位宽度
  adc1_config_channel_atten(ADC_PIN0, ADC_ATTEN);  // 配置ADC通道为0dB衰减器
  adc1_config_channel_atten(ADC_PIN1, ADC_ATTEN);  // 配置ADC通道为0dB衰减器
  adc_chars = (esp_adc_cal_characteristics_t *) malloc(sizeof(esp_adc_cal_characteristics_t));
  esp_adc_cal_value_t val_type = esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN, ADC_WIDTH, DEFAULT_VREF, adc_chars);
  xTaskCreatePinnedToCore(ADC_power, "ADC_power", 2048, NULL, 1, NULL,1);//freeRTOS
}

void ADC_power(void* pvParameters){
  while (1)
  {
    uint32_t adc_reading0 = 0;
    for (int i = 0; i < NO_OF_SAMPLES; i++) {
        adc_reading0 += adc1_get_raw((adc1_channel_t) ADC_PIN0);
        vTaskDelay(1 / portTICK_PERIOD_MS);
    }
    uint32_t adc_reading1 = 0;
    for (int i = 0; i < NO_OF_SAMPLES; i++) {
        adc_reading1 += adc1_get_raw((adc1_channel_t) ADC_PIN1);
        vTaskDelay(1 / portTICK_PERIOD_MS);
    }

    adc_reading0 /= NO_OF_SAMPLES;
    adc_reading1 /= NO_OF_SAMPLES;
    uint32_t voltage0 = esp_adc_cal_raw_to_voltage(adc_reading0, adc_chars);
    uint32_t voltage1 = esp_adc_cal_raw_to_voltage(adc_reading1, adc_chars);
   
    // Serial0.print("ADC Reading: ");
    // Serial0.print(adc_reading0);
    // Serial0.print("Voltage0: ");
    // Serial0.println(voltage0);
    // Serial0.print("Voltage1: ");
    // Serial0.println(voltage1);

    sprintf(char_adc0,"%d",voltage0);
    strcpy(udp_char_adc0, voltageString0); // 将 "Voltage0:" 复制到 result
    strcat(udp_char_adc0, char_adc0); // 将 char_adc0 连接到 result
    // udp_send(udp_char_adc0); 
    
    sprintf(char_adc1,"%d",voltage1);
    strcpy(udp_char_adc1, voltageString1); // 将 "Voltage0:" 复制到 result
    strcat(udp_char_adc1, char_adc1); // 将 char_adc0 连接到 result
    // udp_send(udp_char_adc1); 

    power_mw = voltage1*11*voltage0/10000 ;
    sprintf(char_power_mw,"%d",power_mw);
    strcpy(udp_char_power, powerString); // 将 "Voltage0:" 复制到 result
    strcat(udp_char_power, char_power_mw); // 将 char_adc0 连接到 result   
    // udp_send(udp_char_power);  
    // sprintf(char_adc1,"%d",voltage0);
    // udp_send("\nVoltage1:");  
    // udp_send(udp_char_adc1); 
    // int voltage_ad = analogRead(1);     
    // sprintf(udp_char_adc_no_cal,"%d",voltage_ad); 
    // udp_send("non_cal:");   
    // udp_send(udp_char_adc_no_cal); 
    // delay(100);    
    vTaskDelay(100 / portTICK_PERIOD_MS);

  }

}